package com.tim.file.service;

import com.utils.CamelCaseUtils;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tim
 * @version 1.0
 * @date 2022/12/19 17:55
 */
@Service
public class SqlLiteServer {
    @Autowired
    Statement sqlLiteSql;

    public String getKeyMapName(String oldKeyName) {
        String name = CamelCaseUtils.toCamelCase(oldKeyName);
        return name;
    }

    public List<Map<String, Object>> getAllList() throws SQLException {
        String sql = "select * from sys_t_sql";
        ResultSet resultSet = sqlLiteSql.executeQuery(sql);
        List<Map<String, Object>> list = new ArrayList<>();
        while (resultSet.next()) {
            int col = resultSet.getMetaData().getColumnCount();
            Map<String, Object> map = new HashMap<>();
            for (int i = 1; i < col; i++) {
                String catalogName = resultSet.getMetaData().getColumnName(i);
                Object object = resultSet.getObject(catalogName);
//                System.out.println(catalogName + "============" + object);
                map.put(getKeyMapName(catalogName), object);
            }
            list.add(map);
        }
        return list;
    }


    public Map<String, Object> getItemByGroupsCodes(String groups, String codes) throws SQLException {
        Map<String, Object> param = new HashMap<>();
        param.put("groups", groups);
        param.put("codes", codes);
        String sql = "select * from sys_t_sql where 1=1 and groups = '${groups}' and codes= '${codes}'";
        StringSubstitutor stringSubstitutor = new StringSubstitutor(param);
        String replace = stringSubstitutor.replace(sql);
        ResultSet resultSet = sqlLiteSql.executeQuery(replace);
        while (resultSet.next()) {
            int col = resultSet.getMetaData().getColumnCount();
            Map<String, Object> map = new HashMap<>();
            for (int i = 1; i < col; i++) {
                String catalogName = resultSet.getMetaData().getColumnName(i);
                Object object = resultSet.getObject(catalogName);
                System.out.println(catalogName + "============" + object);
                map.put(getKeyMapName(catalogName), object);
            }
            return map;
        }
        return null;
    }
}
